package com.untour.im.server.handler;

import com.untour.im.codec.constants.IMConstants;
import com.untour.im.server.service.UserChannelService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HeartBeatEventHandler extends ChannelInboundHandlerAdapter {

    private final Long heartBeatTime;

    private final UserChannelService userChannelService;


    public HeartBeatEventHandler(Long heartBeatTime, UserChannelService userChannelService) {
        this.heartBeatTime = heartBeatTime;
        this.userChannelService = userChannelService;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("客户端已断开连接,删除channel");
        userChannelService.removeChannelAndUserCache(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 判断evt是否是IdleStateEvent（用于触发用户事件，包含 读空闲/写空闲/读写空闲 ）
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent)evt;		// 强制类型转换
            log.info("触发了：" + event.state() + "事件");
            if (event.state() == IdleState.READER_IDLE) {
                log.info("读空闲");
                userChannelService.removeChannelAndUserCache(ctx);
            } else if (event.state() == IdleState.WRITER_IDLE) {
                log.info("进入写空闲");
            } else if (event.state() == IdleState.ALL_IDLE) {
                Long lastReadTime = (Long) ctx.channel().attr(AttributeKey.valueOf(IMConstants.ReadTime)).get();
                long now = System.currentTimeMillis();
                if(lastReadTime != null && now - lastReadTime > heartBeatTime){
                    // 退后台逻辑
//                    SessionSocketHolder.offlineUserSession((NioSocketChannel) ctx.channel());
                }
            }
        }
    }
}
